package 双指针系列;

public class ReplaceSpace {
    //第二次做
    //解法一：StringBuilder
    public String replaceSpace3(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<s.length();i++){
            char c =s.charAt(i);
            if(c==' '){
                sb.append("%20");
            }else{
                sb.append(c);
            }
        }
        return new String(sb);
    }
    //解法二：双指针法
    public String replaceSpace4(String s) {
        if(s==null || s.length()==0){
            return s;
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<s.length();i++){
            char c =s.charAt(i);
            if(c==' '){
                sb.append("  ");
            }
        }

        if(sb.length()==0){
            return s;
        }

        int left = s.length()-1;
        s = s + sb.toString();
        int right = s.length()-1;
        char[] chars = s.toCharArray();
        while(left>=0){
            if(chars[left]==' '){
                chars[right--] = '0';
                chars[right--] = '2';
                chars[right] = '%';
            }else{
                chars[right] = chars[left];
            }
            left--; //这一点要写外面，不管是否匹配都要--；
            right--;
        }
        return new String(chars);
    }
    //解法三：双指针简洁法
    public String replaceSpace5(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        char[] array = new char[s.length()*3];
        int right = 0;
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c==' '){
                array[right++] = '%';
                array[right++] = '2';
                array[right++] = '0';
            }else{
                array[right++] = c;
            }
        }
        return new String(array,0,right);
    }
}
